<template>
    <rx-dialog @handOk="handleCompleteCheck" @cancel="closeWindow" :oktext="$ti18('rxForm.commitBtn','提交')" order="buttom" btnalign="center">
        <rx-fit>
            <div style="height:100%;width:100%;padding:20px;">
                <a-form>
                    <a-form-item v-if="rejectOptions && rejectOptions.length>1" :label="i18n('rejectPage.rejectMode','驳回方式')" :label-col="labelCol" :wrapper-col="wrapperCol">
                        <a-radio-group v-model="checkType" :options="rejectOptions">
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item v-if="checkType=='BACK_TO_STARTOR' && !isBatch" :label="i18n('rejectPage.backTaskComplete','回退任务完成后')" :label-col="labelCol" :wrapper-col="wrapperCol">
                        <a-radio-group v-model="nextJumpType">
                            <a-radio value="normal">{{i18n('rejectPage.normal','正常执行')}}</a-radio>
                            <a-radio value="source">{{i18n('rejectPage.backtrack','原路返回')}}</a-radio>
                        </a-radio-group>
                    </a-form-item>

                    <a-form-item v-if="checkType=='BACK_SPEC'" :label="i18n('rejectPage.specifyNodes','指定节点')" :label-col="labelCol" :wrapper-col="wrapperCol">
                        <a-select v-model="destNodeId" style="width:100%">
                            <a-select-option v-for="item in backNodes" :key="item.value" :value="item.value">{{ item.label }}</a-select-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :label="i18n('taskCheck.opinion','意见')" :label-col="labelCol" :wrapper-col="wrapperCol">
                        <a-textarea :placeholder="i18n('taskCheck.opinion','请填写意见','write')" v-model="opinion"></a-textarea>
                    </a-form-item>

                    <a-form-item :label="i18n('taskCheck.attachment','附件')" :label-col="labelCol" :wrapper-col="wrapperCol">
                        <rx-attach-component v-model="fileList" ></rx-attach-component>
                    </a-form-item>

                    <a-form-item :label="i18n('taskCheck.cc','抄送')" :label-col="labelCol" :wrapper-col="wrapperCol">
                        <rx-user-component v-model="copyUsers" :isAccount="true" :single="false"></rx-user-component>
                    </a-form-item>

                </a-form>
            </div>
        </rx-fit>
    </rx-dialog>
</template>
<script>
import { Dialog, RxDialog,RxAttachComponent,RxUserComponent, Util, RxFit, RxTextBoxList } from '@lowcode/jpaas-common-lib'
import BpmtaskApi from '@/api/bpm/core/bpmTask'
import BpmPublicApi from '@/api/bpm/core/BpmPublicApi'
import BpmCheckHistoryApi from "@/api/bpm/core/bpmCheckHistory";
import BpmTaskExecutors from "./BpmTaskExecutors";

export default {
    name: 'bpm-task-back',
    components: {
        RxFit,
        RxTextBoxList,
        RxDialog,
        RxUserComponent,
        RxAttachComponent,
        BpmTaskExecutors
    },
    props: {
        taskId: {
            type: String,
            required: true
        },
        instId: {
            type: String,
            required: true
        },
        defId: {
            type: String,
            required: true
        },
        formJson: String,
        layerid: String,
        lydata: Object,
        destroy: Function,
        backOptions:Array,
        isBatch: Boolean,
        opinionObj:{
            type:Object,
            default:{
                name:"",
                value:""
            }
        }
    },
    data() {
        return {
            labelCol: { span: 4 },
            wrapperCol: { span: 8 },
            msgOptions:[],
            checkType: '',
            nextJumpType:'normal',
            destNodeId: '',
            opinion: '',
            msgTypes: [],
            fileList:[],
            copyUsers: [],
            opinionName:"",
            backConfig:[
                {label: this.i18n('rejectPage.backPreStep','驳回上一步'), value: 'BACK'},
                {label: this.i18n('rejectPage.backToPromoter','驳回到发起人'), value: 'BACK_TO_STARTOR'},
                {label: this.i18n('rejectPage.backToSpecified','驳回到审批节点'), value: 'BACK_SPEC'}
            ],
            rejectOptions:[

            ],
            backNodes:[],
            checkHistorys:[],
        }
    },
    created(){
        let backsTmp=this.backOptions;

        if(this.isBatch){
            backsTmp=['BACK_TO_STARTOR'];
        }
        var tmp=[];
        for(var i=0;i<this.backConfig.length;i++){
            if(backsTmp.contains(this.backConfig[i].value)){
                tmp.push(this.backConfig[i]);
            }
        }
        this.checkType=tmp[0].value;
        this.rejectOptions=tmp;

        this.opinion=this.opinionObj.value;
        this.opinionName=this.opinionObj.name;
        this.initMessageHandler();
        this.initBackNodes();
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"bpmTask",key);
        },
        loadCheckHistory() {
            let self_=this;
            BpmCheckHistoryApi.getCheckHistorys(this.instId).then(res => {
                if(!res || res.length==0){
                    return;
                }
                self_.checkHistorys=res;
                let backToSpecified= {label: self_.i18n('rejectPage.backToSpecified','驳回到指定节点'), value: 'BACK_SPEC'};
                self_.backs.push(backToSpecified);
            });
        },
        initBackNodes(){
            let self_=this;
            BpmtaskApi.getBackNodes(this.taskId).then(res=>{
                self_.backNodes=res.map(item=>{
                    return {label:item.nodeName,value:item.nodeId,multipleType:item.multipleType};
                })
                if(res && res.length>0){
                    self_.loadCheckHistory();
                }
            });
        },
        initMessageHandler(){
            BpmPublicApi.getMessageHandler().then(res=>{
                for(var i=0;i<res.length;i++){
                    var o=res[i];
                    var obj={ label: o.name, value: o.type };
                    this.msgOptions.push(obj);
                }
            })
        },
        handleCompleteCheck() {
            let self = this;
            //抄送用户
            let copyUserIds=this.getCopyUserAccounts();
            let noticeTypes=this.msgTypes.join(",");
            let cmd = {
                taskId: this.taskId,
                checkType: this.checkType,
                nextJumpType: this.nextJumpType,
                opinion: this.opinion,
                msgTypes: noticeTypes,
                copyUserAccounts: copyUserIds,
                formJson:  self.formJson,
                opinionName:self.opinionName,
                opFiles:JSON.stringify(self.fileList)
            }
            if(this.checkType=='BACK_SPEC') {
                if(!this.destNodeId){
                    this.$message.info(this.i18n('rejectPage.specifyNode','请指定节点！'));
                    return;
                }
                cmd.nodeExecutors=this.getNodeUserMap();
                cmd.destNodeId = this.destNodeId;
            }
            BpmtaskApi.checkComplete(cmd).then(resp => {
                if (resp.success) {
                    Util.closeWindow(self,'ok');
                }
            })
        },
        /**
         * 查找审批历史节点最近的审批人作为驳回节点任务人
         * @returns {*[]}
         */
        getNodeUserMap(){
            let userMap= {};
            let userList=[];
            let node= this.backNodes.find(item =>{
                return item.value==this.destNodeId;
            });
            //会签、串签不选择任务人
            if("parallel"==node.multipleType || "sequential"==node.multipleType){
                return userMap;
            }
            let his ={};
            let hisLength=this.checkHistorys.length;
            for(let i=hisLength-1;i>=0;i--){
                let hisObj = this.checkHistorys[i];
                if(hisObj.nodeId == this.destNodeId){
                    his=hisObj;
                    break;
                }
            }
            let user={
                "type": "user",
                "id": his.handlerId,
                "name": his.handlerUserName,
                "account": "",
                "calcType": "none"
            }
            userList.push(user);
            userMap[this.destNodeId]=userList;
            return userMap;
        },
        /**
         * 获取抄送用户。
         * @returns {string}
         */
        getCopyUserAccounts(){
            var accounts=[];
            if(this.copyUsers && this.copyUsers.length>0){
                this.copyUsers.forEach(item=>{
                    accounts.push(item.account);
                })
            }
            return accounts.join(",");
        },
        closeWindow() {
            Util.closeWindow(this, 'cancel')
        }
    }
}
</script>